import React from "react";
import axios from "axios";
import { Button } from "antd";
import G6, {Graph} from "@antv/g6";
import "./index.css";

interface KnowledgeGraphData {
    graph: Graph | null;
    data: object;
}

class KnowledgeGraph extends React.Component<any, KnowledgeGraphData> {

    constructor(props: any) {
        super(props);
        this.state = {
            data: {},
            graph: null
        }
    }

    renderData = (res: any) => {
        this.setState({
            data: res.data
        })
        if (!this.state.graph) {
            this.setState({
                graph: new G6.Graph({
                    container: "graph",
                    width: 800,
                    height: 600,
                    layout: {
                        type: "dagre",
                        nodesep: 10, // 可选
                        ranksep: 30, // 可选
                        controlPoints: true, // 可选
                    },
                    fitView: true,
                    fitCenter: true,
                    autoPaint: true,
                    modes: {
                        default: ['drag-canvas', 'zoom-canvas', 'drag-node']
                    },
                    defaultNode: {
                        type: 'circle',
                        size: 50
                    },
                    defaultEdge: {
                        style: {
                            lineWidth: 3,
                            endArrow: true
                        }
                    }
                })
            })
        }
    }

    postData = () => {
        axios.post('/api/graph').then((res: any) => {
            if (res.status === 200) {
                const nodes = res.data.nodes
                const edges = res.data.edges
                for (const n of nodes) {
                    n['style'] = {
                        label: {
                            value: n.label
                        }
                    }
                }
                for (const e of edges) {
                    e['style'] = {
                        label: {
                            value: e.label
                        }
                    }
                }
                this.renderData(res)
            }
        }).catch(err => {
            console.log(err)
        })
    }
    render(): React.ReactNode {
        const {data, graph} = this.state
        if (graph) {
            graph.data(data)
            graph.render()
        }
        return (
            <div className="container">
                <Button type="primary" onClick={this.postData}>POST</Button>
                <div id="graph"></div>
            </div>
        )
    }
}

export default KnowledgeGraph;